package com.java.teachercode.mycode;

/**
 * @author shkstart
 * @create 2021-01-28 15:08
 */
public class Breadbag {
    private static final int upCount = 300;
    private static final int nowCount = 50;
    private int breadCount;

    public Breadbag(int breadCount) {
        this.breadCount = breadCount;
    }

    public Breadbag() {
        this(nowCount);
    }

    /*
     * 生产面包
     *
     * */
    public synchronized void produce(int count, String name) {

        System.out.println("+" + name + "准备生产" + count + "个面包");
        while (this.breadCount + count > upCount) {
            System.out.println(" + " + name + "准备生产面包：" + count + "个，现有" + this.breadCount + "超出容量。");
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        //生产
        this.breadCount += count;
        //唤醒消费
        System.out.println("+" + name + "生产了" + breadCount + "个面包" + "生产结束");
        this.notifyAll();

    }

    /*
     * 消费面包
     *
     * */
    public synchronized void buyproduct(int count, String name) {

        System.out.println("+" + name + "准备消费" + count + "个面包");
        while (this.breadCount < count + this.breadCount) {
            System.out.println(" + " + name + "准备消费面包：" + count + "个，现有" + this.breadCount + "超出容量。");
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        //消费
        this.breadCount -= count;
        //唤醒生产
        System.out.println("+" + name + "消费了" + breadCount + "个面包" + "消费结束");
        this.notifyAll();

    }
}
